package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    private String method,uri,protocol;
    private Map<String,String> headers = new HashMap<>();;


    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        //获得请求行
        parseRequestLine();
        //获得消息头
        parseHeaders();
        //获得消息正文
        parseContent();

    }
    private void parseRequestLine() throws IOException {
        String line = readLine();
        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];
        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
    }

    private void parseHeaders() throws IOException {
        while (true){
            String line = readLine().toLowerCase();

            if(line.isEmpty())break;
            String[] data = line.split(":");
            headers.put(data[0],data[1]);
        }
        System.out.println(headers);
    }

    private void parseContent(){

    }

    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int b;
        char cur = 'a',pre = 'a';
        StringBuilder stringBuilder = new StringBuilder();
        while ((b = in.read()) != -1){
            cur =(char) b;
            stringBuilder.append(cur);
            if(cur == 10 && pre == 13){
                break;
            }
            pre = cur;
        }
        String line = stringBuilder.toString().trim();
        return line;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public Map<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }
}
